<template>
  <!--
    editForm.vue
    班级信息编辑/新增表单示例
    包含班级基本信息、班级学生管理、下拉选择、表格等
    使用 Element Plus、vxe-table 等组件库
  -->
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <!-- 班级信息表单 -->
      <el-form
        ref="formAddClassAIRef"
        :model="formData"
        :size="layoutStore.defaultFormItemSize"
        :rules="rules"
        label-width="90px"
        label-position="right"
        @submit.prevent
      >
        <el-row :gutter="16">
          <!-- 班级名称输入 -->
          <el-col :span="12">
            <el-form-item label="班级名称" prop="StudentClass.className">
              <el-input
                class="input-item"
                v-model="formData.StudentClass.className"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <!-- 所属校区选择 -->
          <el-col :span="12">
            <el-form-item label="所属校区" prop="StudentClass.schoolId">
              <dept-select
                class="input-item"
                v-model="formData.StudentClass.schoolId"
                placeholder=""
              />
            </el-form-item>
          </el-col>
          <!-- 班级级别下拉选择 -->
          <el-col :span="12">
            <el-form-item label="班级级别" prop="StudentClass.classLevel">
              <el-select
                class="input-item"
                v-model="formData.StudentClass.classLevel"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="classLevelWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in classLevelWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 班长下拉选择 -->
          <el-col :span="12">
            <el-form-item label="班长" prop="StudentClass.leaderId">
              <el-select
                class="input-item"
                v-model="formData.StudentClass.leaderId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="leaderIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in leaderIdWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 完成课时输入 -->
          <el-col :span="12">
            <el-form-item label="完成课时" prop="StudentClass.finishClassHour">
              <el-input-number
                class="input-item"
                v-model="formData.StudentClass.finishClassHour"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <!-- 班级学生管理表格 -->
          <el-col :span="24">
            <table-box
              ref="student"
              :data="studentWidgetDataList"
              style="height: 300px"
              :size="layoutStore.defaultFormItemSize"
              :row-config="{ isCurrent: false, isHover: true }"
              :seq-config="{ startIndex: (studentWidgetCurrentPage - 1) * studentWidgetPageSize }"
              :sort-config="{ remote: false }"
              :hasExtend="true"
              @refresh="studentWidget.refreshTable()"
            >
              <template #operator>
                <el-button
                  type="primary"
                  :size="layoutStore.defaultFormItemSize"
                  @click="onFormFlowSetClassStudentAIClick()"
                >
                  设置班级学生
                </el-button>
              </template>
              <vxe-column
                title="序号"
                type="seq"
                fixed="left"
                :index="studentWidget.getTableIndex"
                :width="80"
              />
              <vxe-column title="学生姓名" field="studentName" />
              <vxe-column title="所在省份" field="provinceIdDictMap.name" />
              <vxe-column title="所在城市" field="cityIdDictMap.name" />
              <vxe-column title="经验等级" field="experienceLevelDictMap.name" />
              <vxe-column title="所属年级" field="gradeIdDictMap.name" />
              <vxe-column title="操作" fixed="right">
                <template v-slot="scope">
                  <el-button
                    link
                    type="primary"
                    :size="layoutStore.defaultFormItemSize"
                    @click.stop="onDeleteStudentClick(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </vxe-column>
              <template v-slot:empty>
                <div class="table-empty unified-font">
                  <img src="@/assets/img/empty.png" />
                  <span>暂无数据</span>
                </div>
              </template>
            </table-box>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <!-- 底部操作按钮 -->
    <el-row class="footer-box" type="flex" justify="end" align="middle">
      <el-button :size="layoutStore.defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="layoutStore.defaultFormItemSize" type="primary" @click="onAddClick()"
        >新增</el-button
      >
    </el-row>
  </div>
</template>

<script lang="ts">
// 组件名称定义
export default {
  name: 'formAddClassAI',
};
</script>

<script setup lang="ts">
// ---------------------- 依赖与工具导入 ----------------------
import { DialogProp } from '@/components/Dialog/types';
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import {
  treeDataTranslate,
  findItemFromList,
  findTreeNodePath,
  findTreeNode,
  stringCase,
} from '@/common/utils';
import { StudentData } from '@/api/generated/studentController';
import { StudentClassData } from '@/api/generated/studentClassController';
import { CourseData } from '@/api/generated/courseController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import {
  StudentController,
  StudentClassController,
  CourseController,
  SysDeptController,
} from '@/api/generated';
import FormFlowSetClassStudentAI from '@/pages/workflow/pages/flowAddClass/formFlowSetClassStudentAI.vue';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

// 路由、布局、上传、通用方法、字典等 hooks
const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } =
  useUpload();
const {
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

// ---------------------- 组件属性定义 ----------------------
const props = withDefaults(
  defineProps<{
    classId?: string | number | undefined;
    subPage?: number | string | boolean;
    saveOnSubmit?: boolean;
    rowData?: ANY_OBJECT;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    subPage: 0,
    classId: undefined,
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);

// ---------------------- 表单数据与类型定义 ----------------------
const formAddClassAIRef = ref();
// 表单数据类型
type FormAddClassAIData = {
  StudentClass: StudentClassData;
};
// 表单数据
const formData = reactive<FormAddClassAIData>({
  StudentClass: {
    // 班级Id
    classId: undefined,
    // 班级名称
    className: undefined,
    // 所属校区
    schoolId: undefined,
    // 班长
    leaderId: undefined,
    // 完成课时
    finishClassHour: undefined,
    // 班级级别
    classLevel: undefined,
    // 创建用户
    createUserId: undefined,
    // 班级创建时间
    createTime: undefined,
    // 班级状态(0: 正常 1: 解散)
    status: undefined,
    // 班级课程数据
    courseList: [],
    // 学生管理数据
    studentList: [],
    sysDept: {
      // 部门Id
      deptId: undefined,
      // 部门名称
      deptName: undefined,
      // 显示顺序
      showOrder: undefined,
      // 父部门Id
      parentId: undefined,
      // 删除标记(1: 正常 -1: 已删除)
      deletedFlag: undefined,
      // 创建者Id
      createUserId: undefined,
      // 更新者Id
      updateUserId: undefined,
      // 创建时间
      createTime: undefined,
      // 更新时间
      updateTime: undefined,
    },
  },
});
// ---------------------- 表单验证规则 ----------------------
const rules = reactive({
  'StudentClass.schoolId': [{ required: true, message: '请输入所属校区', trigger: 'blur' }],
  'StudentClass.className': [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  'StudentClass.leaderId': [{ required: true, message: '请输入班长', trigger: 'blur' }],
  'StudentClass.classLevel': [{ required: true, message: '请输入班级级别', trigger: 'blur' }],
  'StudentClass.finishClassHour': [
    { required: true, message: '请输入完成课时', trigger: 'blur' },
    {
      type: 'integer',
      message: '完成课时只允许输入整数',
      trigger: 'blur',
      transform: value => Number(value),
    },
    {
      type: 'number',
      min: 0,
      message: '完成课时必须大于0',
      trigger: 'blur',
      transform: value => Number(value),
    },
  ],
});
const instance = getCurrentInstance();

// ---------------------- 事件处理 ----------------------
// 取消按钮事件
const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  }
};

// 是否为编辑模式
const isEdit = computed(() => {
  return props.saveOnSubmit ? props.classId != null : props.rowData != null;
});

// ---------------------- 数据加载与初始化 ----------------------
// 初始化页面数据
const loadStudentClassData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.StudentClass = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      classId: props.classId,
    };
    StudentClassController.view(params)
      .then(res => {
        formData.StudentClass = { ...res.data };
        if (formData.StudentClass.sysDept == null) {
          formData.StudentClass.sysDept = {
            deptId: undefined,
            deptName: undefined,
            showOrder: undefined,
            parentId: undefined,
            deletedFlag: undefined,
            createUserId: undefined,
            updateUserId: undefined,
            createTime: undefined,
            updateTime: undefined,
          };
        }
        studentWidget.refreshTable();
        resolve();
      })
      .catch(e => {
        reject(e);
      });
  });
};
/**
 * 班级级别下拉数据获取函数
 * @returns Promise<ListData<DictData>>
 */
const loadClassLevelDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ClassLevel', itemIdType: 'Integer' })
      .then(res => {
        resolve({
          dataList: res.getList(),
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
// 班级级别下拉配置与组件
const classLevelOptions: DropdownOptions<DictData> = {
  loadData: loadClassLevelDropdownList,
  isTree: false,
};
const classLevelWidget = useDropdown(classLevelOptions);
const { dropdownList: classLevelWidgetDropdownList } = classLevelWidget;
/**
 * 班长下拉数据获取函数
 * @returns Promise<ListData<DictData>>
 */
const loadLeaderIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {};
    DictionaryController.dictStudent(params)
      .then(res => {
        resolve({
          dataList: res.getList(),
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
// 班长下拉配置与组件
const leaderIdOptions: DropdownOptions<DictData> = {
  loadData: loadLeaderIdDropdownList,
  isTree: false,
};
const leaderIdWidget = useDropdown(leaderIdOptions);
const { dropdownList: leaderIdWidgetDropdownList } = leaderIdWidget;
/**
 * 学生管理数据获取函数，返回Promise
 * @param params 查询参数
 */
const loadStudentWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    classId: props.classId || formData.StudentClass.classId,
  };
  return new Promise((resolve, reject) => {
    StudentClassController.listClassStudent(params)
      .then(res => {
        // 级联更新设置临时唯一id
        let tempTime = new Date().getTime();
        nextTick(() => {
          formData.StudentClass.studentList = studentWidgetDataList.value;
        });
        resolve({
          dataList: res.data.dataList.map((item, index) => {
            return {
              __cascade_add_temp_id__: tempTime + index,
              ...item,
            };
          }),
          totalCount: res.data.totalCount,
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
/**
 * 学生管理数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadStudentVerify = () => {
  return true;
};
/**
 * 设置班级学生弹窗
 */
const onFormFlowSetClassStudentAIClick = (row?: StudentData) => {
  let params = {
    saveOnSubmit: false,
    selectIdList: studentWidgetDataList.value.map(item => item.studentId),
  };

  Dialog.show('设置班级学生', FormFlowSetClassStudentAI, { area: ['1200px', '90px'] }, params)
    .then(res => {
      if (Array.isArray(res)) {
        let tempTime = new Date().getTime();
        studentWidgetDataList.value.push(
          ...res.map((item, index) => {
            return {
              ...item,
              // 级联添加每次添加后并不保存到数据库，设置临时的唯一值
              __cascade_add_temp_id__: tempTime + index,
            };
          }),
        );
        formData.StudentClass.studentList = studentWidgetDataList.value;
      }
    })
    .catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 删除学生
 */
const onDeleteStudentClick = (row?: StudentData) => {
  ElMessageBox.confirm('是否删除选中数据？')
    .then(res => {
      studentWidgetDataList.value = studentWidgetDataList.value.filter(item => {
        return item.__cascade_add_temp_id__ !== row?.__cascade_add_temp_id__;
      });
      formData.StudentClass.studentList = studentWidgetDataList.value;
    })
    .catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
// 学生管理表格组件参数与实例
const studentOptions: TableOptions<StudentData> = {
  loadTableData: loadStudentWidgetData,
  verifyTableParameter: loadStudentVerify,
  paged: false,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
const student = ref();
const studentWidget = useTable(studentOptions);
const {
  dataList: studentWidgetDataList,
  currentPage: studentWidgetCurrentPage,
  pageSize: studentWidgetPageSize,
  totalCount: studentWidgetTotalCount,
} = studentWidget;
// 上传相关事件
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
// 刷新表单
const refreshFormAddClassAI = () => {
  // 刷新段落
  studentWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormAddClassAI = () => {
  refreshFormAddClassAI();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormAddClassAI();
};
/**
 * 新增/保存按钮事件
 */
const onAddClick = () => {
  formAddClassAIRef.value.validate(valid => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.StudentClass,
      };
      retFormData.classLevelDictMap = findItemFromList(
        classLevelWidgetDropdownList.value,
        retFormData.classLevel,
        'id',
      );
      retFormData.leaderIdDictMap = findItemFromList(
        leaderIdWidgetDropdownList.value,
        retFormData.leaderId,
        'id',
      );
      props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      classStudentDtoList: (formData.StudentClass.studentList || [])
        .map(item => item.classStudent)
        .filter(item => item != null),
      studentClassDto: {
        className: formData.StudentClass.className,
        schoolId: formData.StudentClass.schoolId,
        leaderId: formData.StudentClass.leaderId,
        finishClassHour: formData.StudentClass.finishClassHour,
        classLevel: formData.StudentClass.classLevel,
      },
    };

    let httpCall = isEdit.value ? StudentClassController.update : StudentClassController.add;
    httpCall(params)
      .then(res => {
        ElMessage.success('新增成功');
        props.dialog?.submit();
      })
      .catch(e => {
        // TODO: 异常处理
        console.error(e);
      });
  });
};
// 表单初始化
const formInit = () => {
  loadStudentClassData()
    .then(res => {
      classLevelWidget.onVisibleChange(true).catch(e => {
        console.error(e);
      });
      leaderIdWidget.onVisibleChange(true).catch(e => {
        console.error(e);
      });
      if (isEdit.value) refreshFormAddClassAI();
    })
    .catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};

// ---------------------- 生命周期钩子 ----------------------
onMounted(() => {
  formInit();
});
</script>
